import datetime
import sys
import traceback

from apps.sql_app.mmongodb import Coll


async def all_client_back_callback(*args, **kwargs):
    """
        处理返回值 确定是否进行存储
    :param self:
    :return:
    """
    from app_main import request_ctx_var
    from main import app
    from apps.file_uploadfile.models import ServerErrModel
    try_his = request_ctx_var.get().state.try_his
    try_his.append(traceback.format_exc())
    request = request_ctx_var.get()
    m = ServerErrModel().dict()
    test_html = request_ctx_var.get().state.proxy_html
    m["ip_port"] = app.state.ip + ":" + str(app.state.port)
    m["client_ip"] = str(request.client.host)
    m["write_time"] = str(datetime.datetime.now())
    m["request_url"] = str(request.url)
    # https://github.com/tiangolo/fastapi/issues/1216 作者目前还没有解决这个bug
    # m.request_body = body.decode()
    m["request_body"] = str(request.state.mbody)
    m["err_type"] = str(sys.exc_info()[0])
    m["err_msg"] = str(sys.exc_info()[1])
    m["traceback_str"] = traceback.format_exc()
    m["test"] = test_html
    save_dicts = ServerErrModel.parse_obj(m)
    m_result = Coll.get_server_exception()
    exception_list = ["proxy"]
    for i in exception_list:
        if i in traceback.format_exc():
            result = await m_result.insert_one(save_dicts.dict(by_alias=True))
            return False, {"traceback": traceback.format_exc(), "need_save": False}
    return False, {"traceback": traceback.format_exc(), "need_save": True}
